package com.xl.adminserver.v2.sdkclients;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.util.Map;
@Slf4j
public class ClientFactory {

    private static Map<String, Object> clientMaps = Maps.newConcurrentMap();
    private static RetryTemplate retryTemplate = createReTryTemplate();

    private ClientFactory() {
    }

    public static <T> T createClient(String baseUrl, Class<T> clientClass) {
        if (clientMaps.containsKey(baseUrl)) {
            return (T) clientMaps.get(baseUrl);
        }
        //日志拦截
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        //重试请求 重试3次，
        Interceptor retryInterceptor = retryInterceptor();
        //更换请求对象
        OkHttpClient client = new OkHttpClient.Builder().
                retryOnConnectionFailure(true)
                .addInterceptor(logging)
                .addInterceptor(retryInterceptor) //添加重试机制
                .build();
        //序列化方式
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
        //                .addConverterFactory(JacksonConverterFactory.create())
        //构建客户端
        Retrofit retrofit = new Retrofit.Builder().client(client)
                .baseUrl(baseUrl)
                .addConverterFactory(gsonConverterFactory)
                .build();
        // 返回实例
        return retrofit.create(clientClass);
    }

    private static RetryTemplate createReTryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        simpleRetryPolicy.setMaxAttempts(3);
        retryTemplate.setRetryPolicy(simpleRetryPolicy);
        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        backOffPolicy.setInitialInterval(3000);
        retryTemplate.setBackOffPolicy(backOffPolicy);
        return retryTemplate;
    }

    /**
     * 自定义的，重试N次的拦截器
     * 通过：addInterceptor 设置
     */
    private static Interceptor retryInterceptor( ) {
        return new Interceptor() {

            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                return retryTemplate.execute(content -> {
                    log.info("出现异常，开始重试:{}",content);
                    Request request = chain.request();
                    return chain.proceed(request);
                });
            }
        };
    }

}
